package com.rogchen.security.securitycustomuser.configuration.permission;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Rogchen rogchen128@gmail.com
 * @description:
 * @product: IntelliJ IDEA
 * @created Date: 19-11-15 11:30
 **/
@Component
public class RsbPermissionImpl implements RsbPermission {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        boolean hasPermission = false;
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            String username = ((UserDetails) principal).getUsername();
            // TODO 根据用户名去加载数据库中的用户对应的权限
            List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
            for (SimpleGrantedAuthority authority : authorities) {
                if (antPathMatcher.match(authority.getAuthority(), request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
